/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcDetailActivity.java
 *   @Date: 19-1-15 下午7:08
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.otc.presenter.OtcDetailPresenter;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.view.ClickProxy;
import io.bhex.app.view.InputView;
import io.bhex.app.view.PointLengthFilter;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.NumberUtils;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.otc.OtcConstant;
import io.bhex.sdk.otc.bean.OtcConfigResponse;
import io.bhex.sdk.otc.bean.OtcCreateOrderRequestBean;
import io.bhex.sdk.otc.bean.OtcItemSimpleResponse;
import io.bhex.sdk.otc.bean.OtcListResponse;
import io.bhex.sdk.otc.bean.OtcUserInfo;

public class OtcDetailActivity extends BaseActivity<OtcDetailPresenter,OtcDetailPresenter.OtcDetailUI> implements OtcDetailPresenter.OtcDetailUI, View.OnClickListener {

    private TopBar topBar;
    private InputView inputTotalPrice;
    private InputView inputBuySellNum;
    private InputView inputFundPwd;
    private Button btnCreateOrder;
    private boolean isBuy;
    private long startTime;
    private long endTime;
    private OtcListResponse.OtcItemBean itemBean;
    private OtcItemSimpleResponse currentOtcItemSimple;
    private int baseDigit=AppData.Config.DIGIT_DEFAULT_VALUE;
    private boolean isChangingOfAmount=false;
    private boolean isChangingOfPrice=false;
    private OtcConfigResponse configBean;
//    private OtcConfigResponse.TokenBean currentTokenConfig;
    //下单依据flag默认是数量
    private boolean isFlagQuantity=true;
    private int currencyDigit = AppData.DIGIT_LEGAL_MONEY;
    private PointLengthFilter pricePointFilter;
    private PointLengthFilter numPointFilter;
    private OtcUserInfo currentOtcUserInfo;
    private boolean isTrade=true;
    private String currentFree="";
    private OtcListResponse.OtcItemBean.TokenConfigBean currentTokenConfig;

    @Override
    protected int getContentView() {
        return R.layout.activity_otc_detail_layout;
    }

    @Override
    protected OtcDetailPresenter createPresenter() {
        return new OtcDetailPresenter();
    }

    @Override
    protected OtcDetailPresenter.OtcDetailUI getUI() {
        return this;
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置禁止系统截屏、录制
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
    }

    @Override
    protected void initView() {
        super.initView();
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        inputBuySellNum = viewFinder.find(R.id.buySellNum);
        inputBuySellNum.setPaddingRight(PixelUtils.dp2px(40));
        inputBuySellNum.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        inputTotalPrice = viewFinder.find(R.id.totalPrice);
        inputTotalPrice.setPaddingRight(PixelUtils.dp2px(40));
        inputTotalPrice.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        inputFundPwd = viewFinder.find(R.id.fundPwd);
        btnCreateOrder = viewFinder.find(R.id.btnCreateOrder);

        numPointFilter = new PointLengthFilter();
        inputBuySellNum.getEditText().setFilters(new InputFilter[]{numPointFilter});
        pricePointFilter = new PointLengthFilter();
        inputTotalPrice.getEditText().setFilters(new InputFilter[]{pricePointFilter});

        Intent intent = getIntent();
        if (intent != null) {
            itemBean = (OtcListResponse.OtcItemBean) intent.getSerializableExtra("item");
            configBean = (OtcConfigResponse) intent.getSerializableExtra("config");
//            handleConfig(configBean);
            showDetailInfo(itemBean);
        }

    }

//    private void handleConfig(OtcConfigResponse configBean) {
//        List<OtcConfigResponse.CurrencyBean> currencyBeanList = configBean.getCurrency();
//        //深度共享 每个单子
//        //        if (currencyBeanList != null) {
////            for (OtcConfigResponse.CurrencyBean currencyBean : currencyBeanList) {
////                if (currencyBean.getCurrencyId().equals(itemBean.getCurrencyId())) {
////                    currencyDigit = currencyBean.getAmountScale();
////                    pricePointFilter.setDecimalLength(currencyDigit);
////                }
////
////            }
////        }
//        List<OtcConfigResponse.TokenBean> tokenList = configBean.getToken();
//        if (tokenList != null) {
//            for (OtcConfigResponse.TokenBean tokenBean : tokenList) {
//                String tokenId = tokenBean.getTokenId();
//                if (tokenId.equals(itemBean.getTokenId())) {
//                    currentTokenConfig = tokenBean;
//                    baseDigit = currentTokenConfig.getScale();
//                    numPointFilter.setDecimalLength(baseDigit);
//                }
//            }
//        }
//    }

    @Override
    protected void onResume() {
        super.onResume();
        requestOtcDetail();
    }


    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.btnCreateOrder).setOnClickListener(new ClickProxy(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createOrder();
            }
        }));
        viewFinder.find(R.id.surplus_quantity).setOnClickListener(this);
        viewFinder.find(R.id.avaliable_amount).setOnClickListener(this);
        inputBuySellNum.addTextWatch(numTextWatcher);
        inputTotalPrice.addTextWatch(priceTextWatcher);
//        inputBuySellNum.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                isChangingOfAmount = hasFocus;
//            }
//        });
//        inputTotalPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                isChangingOfPrice = hasFocus;
//            }
//        });
    }

    @Override
    public void showIsShowRiskTips(boolean isShowRiskTips) {
        if (itemBean != null) {
            String tokenId = itemBean.getTokenId();
            if (!TextUtils.isEmpty(tokenId)) {
                viewFinder.find(R.id.tip_risk).setVisibility(isShowRiskTips && KlineUtils.isRiskTokenId(tokenId) ? View.VISIBLE : View.GONE);
            }
        }
    }

    /**
     * 下单
     */
    private void createOrder() {
        String num = inputBuySellNum.getInputString();
        String totalPrice = inputTotalPrice.getInputString();
        String fundPasswd = inputFundPwd.getInputString();
        if (TextUtils.isEmpty(num)) {
            ToastUtils.showLong(this,getString(R.string.string_input_please)+getString(isBuy?R.string.string_otc_buy:R.string.string_otc_sell)+getString(R.string.string_amount));
            return;
        }

        if (currentTokenConfig != null) {
            String minQuote = currentTokenConfig.getMinQuote();
            String maxQuote = currentTokenConfig.getMaxQuote();
            if (NumberUtils.sub(num,minQuote)<0||NumberUtils.sub(num,maxQuote)>0) {
                ToastUtils.showLong(this,getString(R.string.string_format_input_otc_quote,minQuote,maxQuote));
//                        inputBuySellNum.setError(getString(R.string.string_format_input_otc_quote,minQuote,maxQuote));
                return;
            }
        }

        if (TextUtils.isEmpty(totalPrice)) {
            ToastUtils.showLong(this,getString(R.string.string_input_please)+getString(R.string.string_hint_total_price));
            return;
        }

        if (itemBean!=null){
//                最小下单金额：最小下单金额不能小于XXCNY
            String minAmount = itemBean.getMinAmount();
            if (NumberUtils.sub(totalPrice,minAmount)<0) {
                ToastUtils.showLong(this, getString(R.string.string_otc_create_order_not_be_less_tips)+minAmount+itemBean.getCurrencyId());
                return;
            }
            String maxAmount = itemBean.getMaxAmount();
            if (NumberUtils.sub(totalPrice,maxAmount)>0){
//                        最大下单金额：最大下单金额不能大于XXCNY
                ToastUtils.showLong(this,getString(R.string.string_otc_create_order_not_be_greater_tips)+maxAmount+itemBean.getCurrencyId());
                return;
            }
        }

        if (!isTrade&&TextUtils.isEmpty(fundPasswd)) {
            ToastUtils.showLong(this,getString(R.string.string_input_please)+getString(R.string.string_finance_passwd));
            return;
        }
        endTime = System.currentTimeMillis();
        if (endTime-startTime>OtcConstant.OTC_CREATE_ORDER_DEFAULT_TIMEOUT) {
            clearInputData();
            requestOtcDetail();
            ToastUtils.showLong(this,getString(R.string.string_otc_create_order_timeout_tips));
            return;
        }
        OtcCreateOrderRequestBean otcCreateOrderRequestBean = new OtcCreateOrderRequestBean();
        otcCreateOrderRequestBean.itemId = itemBean.getId();
        otcCreateOrderRequestBean.tokenId = itemBean.getTokenId();
        otcCreateOrderRequestBean.currencyId = itemBean.getCurrencyId();
        otcCreateOrderRequestBean.side = isBuy?0:1;
        otcCreateOrderRequestBean.price = currentOtcItemSimple.getPrice();
        otcCreateOrderRequestBean.quantity = num;
        otcCreateOrderRequestBean.amount = totalPrice;
        otcCreateOrderRequestBean.curPrice = currentOtcItemSimple.getCurPrice();
        otcCreateOrderRequestBean.tradePwd = fundPasswd;
        otcCreateOrderRequestBean.flag = isFlagQuantity?"quantity":"amount";

        getPresenter().createOtcOrder(isBuy,otcCreateOrderRequestBean);
    }

    private void showDetailInfo(OtcListResponse.OtcItemBean response) {
        OtcListResponse.OtcItemBean.TokenConfigBean tokenConfig = response.getTokenConfig();
        if (tokenConfig != null) {
            currentTokenConfig = tokenConfig;
            baseDigit = currentTokenConfig.getScale();
            numPointFilter.setDecimalLength(baseDigit);

        }
        OtcListResponse.OtcItemBean.CurrencyConfigBean currencyConfig = response.getCurrencyConfig();
        if (currencyConfig != null) {
            currencyDigit = currencyConfig.getAmountScale();
        }
        pricePointFilter.setDecimalLength(currencyDigit);
        viewFinder.textView(R.id.user_name).setText(response.getNickName());
        viewFinder.textView(R.id.turnoverRate).setText( "（"+response.getRecentOrderNum()+"/"+response.getRecentExecuteRate()+"%）");
        viewFinder.textView(R.id.price).setText(response.getPrice());
        viewFinder.textView(R.id.limit_price).setText(response.getMinAmount()+" - "+response.getMaxAmount()+" "+response.getCurrencyId());
        viewFinder.textView(R.id.surplus_quantity).setText(response.getLastQuantity()+" "+response.getTokenName());
        viewFinder.textView(R.id.buySellNumUnit).setText(response.getTokenName());
        viewFinder.textView(R.id.totalPriceUnit).setText(response.getCurrencyId());
        List<Integer> payments = response.getPayments();
        if (payments != null) {
            viewFinder.find(R.id.support_pay_unionpay).setVisibility(payments.contains(0)?View.VISIBLE:View.GONE);
            viewFinder.find(R.id.support_pay_alipay).setVisibility(payments.contains(1)?View.VISIBLE:View.GONE);
            viewFinder.find(R.id.support_pay_wechat).setVisibility(payments.contains(2)?View.VISIBLE:View.GONE);
        }

        if (response.getSide()==0) {
            //出售
            isBuy = false;

            topBar.setTitle(getString(R.string.string_otc_sell)+" "+response.getTokenName());
            inputBuySellNum.setInputHint(getString(R.string.string_amount));
            viewFinder.textView(R.id.title_user_info).setText(getString(R.string.string_otc_buyer));
        }else{
            isBuy = true;
            topBar.setTitle(getString(R.string.string_otc_buy)+" "+response.getTokenName());
            inputBuySellNum.setInputHint(getString(R.string.string_amount));
            viewFinder.textView(R.id.title_user_info).setText(getString(R.string.string_otc_seller));
        }

        String remark = response.getRemark();
        if (!TextUtils.isEmpty(remark)) {
            viewFinder.find(R.id.remark_title).setVisibility(View.VISIBLE);
            viewFinder.find(R.id.remark).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.remark).setText(remark);
        }
    }

    private void requestOtcDetail() {
        if (itemBean != null) {
            getPresenter().getOtcDetail(itemBean);
            if (itemBean.getSide()==0) {
                //出售才获取余额
                getPresenter().getAvaliableAsset(itemBean);
//                viewFinder.find(R.id.divider).setVisibility(View.VISIBLE);
//                viewFinder.find(R.id.avaliable_amount).setVisibility(View.VISIBLE);
            }else{
//                viewFinder.find(R.id.divider).setVisibility(View.GONE);
//                viewFinder.find(R.id.avaliable_amount).setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void showOtcDetail(OtcItemSimpleResponse response) {
        startTime = System.currentTimeMillis();
        currentOtcItemSimple = response;
        if (itemBean != null) {
            itemBean.setPrice(currentOtcItemSimple.getPrice());
            itemBean.setLastQuantity(currentOtcItemSimple.getLastQuantity());
            viewFinder.textView(R.id.price).setText(response.getPrice());
            viewFinder.textView(R.id.surplus_quantity).setText(response.getLastQuantity()+" "+itemBean.getTokenName());
        }
    }

    @Override
    public void needRefreshOtcDetail() {
        requestOtcDetail();
    }

    @Override
    public void showOtcUserInfo(OtcUserInfo response) {
        currentOtcUserInfo = response;
        int tradeFlag = currentOtcUserInfo.getTradeFlag();
        isTrade = tradeFlag ==1;
        viewFinder.find(R.id.fundPwdRela).setVisibility(isTrade?View.GONE:View.VISIBLE);
    }

    @Override
    public void updateAssettByToken(OtcListResponse.OtcItemBean otcItemBean, String free) {
        if (itemBean != null) {
            if (!itemBean.getTokenId().equals(otcItemBean.getTokenId())) {
                //当前币种
                return;
            }
        }
        currentFree = free;
        viewFinder.find(R.id.divider).setVisibility(View.VISIBLE);
        viewFinder.find(R.id.avaliable_amount).setVisibility(View.VISIBLE);
        viewFinder.textView(R.id.avaliable_amount).setText(getString(R.string.string_finance_avaliable_amount)+": "+ NumberUtils.roundFormatDown(free, AppData.Config.DIGIT_DEFAULT_VALUE)+" "+otcItemBean.getTokenName());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.avaliable_amount:
                if (!TextUtils.isEmpty(currentFree)) {
                    inputBuySellNum.setInputString(NumberUtils.roundFormatDown(currentFree,baseDigit));
                }
                break;
            case R.id.surplus_quantity:
                if (currentOtcItemSimple != null) {
                    inputBuySellNum.setInputString(currentOtcItemSimple.getLastQuantity());
                }
                break;

        }
    }

    private void clearInputData() {
        inputBuySellNum.setInputString("");
        inputTotalPrice.setInputString("");
    }

    private TextWatcher numTextWatcher = new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (isChangingOfPrice){
                return;
            }
            isChangingOfAmount = true;
            String num = s.toString();
            if (!TextUtils.isEmpty(num) && currentOtcItemSimple != null) {
                String price = currentOtcItemSimple.getPrice();
                String totalPrice = NumberUtils.roundFormatDown(NumberUtils.mul(num,price),currencyDigit);
                inputTotalPrice.setInputString(totalPrice);
            }else{
                inputTotalPrice.setInputString("");
            }
            isFlagQuantity = true;
            isChangingOfAmount = false;
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    private TextWatcher priceTextWatcher = new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (isChangingOfAmount){
                return;
            }
            isChangingOfPrice= true;
            String totalPrice = s.toString();
            if (!TextUtils.isEmpty(totalPrice) && currentOtcItemSimple != null) {
                String price = currentOtcItemSimple.getPrice();
                String num = NumberUtils.roundFormatDown(NumberUtils.div(price,totalPrice),baseDigit);
                inputBuySellNum.setInputString(num);
            }else{
                inputBuySellNum.setInputString("");
            }
            isFlagQuantity = false;
            isChangingOfPrice= false;
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
}
